package com.wanxi.Controller;

import com.github.pagehelper.PageInfo;
import com.wanxi.Service.HFMService;
import com.wanxi.pojo.Ledger;
import com.wanxi.pojo.MMjson;
import com.wanxi.pojo.MonthIE;
import com.wanxi.pojo.User;
import com.wanxi.pojo.query.LedgerQuery;
import com.wanxi.pojo.query.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Controller
public class HFMController {
    int loginUserId;
    private HFMService HFMService;

    @Autowired
    public HFMController(HFMService HFMService) {
        this.HFMService = HFMService;
    }

    /**
     * 登入 界面渲染
     */
    @GetMapping("/login")
    public String show() {
        return "login";
    }

    /**
     * 进行登陆验证
     * <hr>
     * 成功则跳转账本查看界面
     * <br>
     * 失败则刷新界面
     */
    @PostMapping("/login")
    public String login(@RequestParam int userid, @RequestParam String userpassword, RedirectAttributes attributes) {
        //验证身份
        if (HFMService.login(userid, userpassword)) {
            loginUserId = userid;
            return "redirect:/ledger";
        } else {
            attributes.addFlashAttribute("message", "账号或密码错误");
            return "redirect:/login";
        }
    }

    /**
     * 查看账本 界面渲染
     */
    @GetMapping("/ledger")
    public String ledger(Model model, LedgerQuery ledgerQuery, RedirectAttributes attributes) {
        //判断是否登入
        if (loginUserId == 0) {
            attributes.addFlashAttribute("message", "请登入！");
            return "redirect:/login";
        } else {
            PageInfo<Ledger> ledgerPageInfo = HFMService.ledger(ledgerQuery, loginUserId);
            model.addAttribute("page", ledgerPageInfo);
            return "ledger";
        }
    }

    /**
     * 根据时间查询账本
     */
    @PostMapping("/ledger")
    public String ledgerByTime(Model model, LedgerQuery ledgerQuery) {
        PageInfo<Ledger> ledgerPageInfo = HFMService.ledger(ledgerQuery, loginUserId);
        model.addAttribute("page", ledgerPageInfo);
        return "ledger";
    }


    /**
     * 添加账单 界面渲染
     */
    @GetMapping("/addledger")
    public String addledger(Model model) {
        //判断是否登入
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        model.addAttribute("IENames", HFMService.getIEName());
        model.addAttribute("CardBanks", HFMService.getCardBank(loginUserId));
        Ledger ledger = new Ledger();
        model.addAttribute("ledger", ledger);
        return "addledger";
    }

    /**
     * 处理添加账单
     */
    @PostMapping("/addledger")
    public String addledger(Ledger ledger, RedirectAttributes attributes) {
        if (HFMService.addLedger(ledger, loginUserId)) {
            attributes.addFlashAttribute("message", " 添加账单成功");
        } else {
            attributes.addFlashAttribute("message", " 添加账单失败");
        }
        return "redirect:/ledger";
    }

    /**
     * 用户展示
     */
    @GetMapping("/usertable")
    public String usertable(Model model, UserQuery userQuery, RedirectAttributes attributes) {
        //判断是否登入
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        //判断是否为root
        if (HFMService.RorU(loginUserId)) {
            //如果是则跳转到用户列表
            PageInfo<User> userPageInfo = HFMService.userListByName(userQuery);
            model.addAttribute("page", userPageInfo);
            return "usertable";
        } else {
            //如果不是，刷新当前界面
            attributes.addFlashAttribute("message", "你不是root用户，无法访问用户列表");
            return "redirect:/ledger";
        }
    }

    /**
     * 根据时间查询用户
     */
    @PostMapping("/usertable")
    public String listUserByTime(Model model, UserQuery userQuery) {
        PageInfo<User> userPageInfo = HFMService.userListByName(userQuery);
        model.addAttribute("page", userPageInfo);
        return "usertable";
    }

    /**
     * 删除用户
     *
     * @param userID
     */
    @GetMapping("/delete/{userid}")
    public String delete(@PathVariable("userid") Integer userID, RedirectAttributes attributes) {
        //判断是否登入
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        boolean b = HFMService.deleteUserById(userID);
        if (b) {
            attributes.addFlashAttribute("message", "删除用户成功");
        } else {
            attributes.addFlashAttribute("message", "删除用户失败");
        }
        return "redirect:/usertable";
    }


    /**
     * 新增用户>跳转到修改界面
     * <br>
     * 传过去一个id=0的user
     */
    @GetMapping("/adduser")
    public String adduser(Model model) {
        //判断是否登入
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        model.addAttribute("user", new User());
        return "userUpData";
    }

    /**
     * 修改用户>跳转到修改界面
     * <br>
     * 传过去一个有id的用户
     */
    @GetMapping("/userUpData/{userid}")
    public String upUserData(@PathVariable Integer userid, Model model) {
        //判断是否登入
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        model.addAttribute("user", HFMService.queryUserId(userid));
        return "userUpData";
    }

    /**
     * 修改界面提交到这里
     * <br>
     * 根据有无id判断是添加还是修改
     *
     * @param user
     */
    @PostMapping("/userUpData")
    public String userUpData(User user, RedirectAttributes attributes) {
        UserQuery userQuery = new UserQuery();
        int id = user.getUserid();
        userQuery.setUsername(user.getUsername());
        PageInfo<User> userPageInfo = HFMService.userListByName(userQuery);
        //id不为空，则为修改
        if (id != 0) {
            if (userPageInfo.getSize() == 0) {
                if (HFMService.upDateUser(user)) {
                    attributes.addFlashAttribute("message", " 更新用户成功");
                } else {
                    attributes.addFlashAttribute("message", "更新用户失败");
                }
                return "redirect:/usertable";
            } else {
                attributes.addFlashAttribute("message", "该用户名已存在");
                return "redirect:/userUpData/" + user.getUserid();
            }
        } else {
            if (userPageInfo.getSize() == 0) {
                if (HFMService.addUser(user)) {
                    attributes.addFlashAttribute("message", " 新增用户成功");
                } else {
                    attributes.addFlashAttribute("message", "新增用户失败");
                }
            } else {
                attributes.addFlashAttribute("message", "该用户名已存在");
            }
            return "redirect:/usertable";
        }
    }

    @GetMapping("/yearMoney")
    public String getYear(Model model, RedirectAttributes attributes) {
        //判断是否登入
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        //判断是否为root
        if (!HFMService.RorU(loginUserId)) {
            //如果不是，退回账本界面
            attributes.addFlashAttribute("message", "你不是root用户，无法访问用户列表");
            return "redirect:/ledger";

        } else {
            //如果是，则渲染
            model.addAttribute("yearlist", HFMService.listYear());
            return "yearMoney";
        }
    }

    @PostMapping("/yearMoney")
    public String listYearMoney(int yearchosen, Model model) {
        List<List<Integer>> datalist = HFMService.yearMoney(yearchosen);
        int index = 1; // 从1开始，以便与你的data1Json, data2Json等命名一致
        for (List<Integer> list : datalist) {
            String jsonName = "data" + index + "Json"; // 构建属性名，如data1Json, data2Json等
            String jsonString = JSON.toJSONString(list); // 将数据对象转换为JSON字符串
            model.addAttribute(jsonName, jsonString); // 将JSON字符串添加到模型中
            index++; // 递增索引值
        }
        model.addAttribute("yearlist", HFMService.listYear());
        return "yearMoney";
    }

    @GetMapping("/monthMoney")
    public String getMonth(Model model, RedirectAttributes attributes) {
        if (loginUserId == 0) {
            return "redirect:/ledger";
        }
        model.addAttribute("monthIE", new MonthIE());
        List<Integer> monthlist = IntStream.rangeClosed(1, 12)
                .boxed()
                .collect(Collectors.toList());
        model.addAttribute("yearlist", HFMService.listYear());
        model.addAttribute("monthlist", monthlist);
        model.addAttribute("userlist", HFMService.listUser());
        return "monthMoney";
    }

    @PostMapping("/monthMoney")
    public String listMonthMoney(MonthIE monthIE, Model model, RedirectAttributes attributes) {
        //不是root用户时访问内容不属于自己时
        if (!HFMService.RorU(loginUserId) && monthIE.getUserid() != loginUserId) {
            attributes.addFlashAttribute("message", "你不是root用户，只能查看自己数据");
            return "redirect:/ledger";
        }
        //将获取的数据传给前端
        List<MMjson> mmIE = HFMService.getMonthIE(monthIE);
        String IEdata = JSON.toJSONString(mmIE);
        System.out.println(IEdata);
        model.addAttribute("IEdata", IEdata);
        return getMonth(model, attributes);
    }

    @GetMapping("/demo")
    public String demo() {
        return "demo";
    }

    @PostMapping("/demo")
    public String demo1() {
        return "demo";
    }
}
